package com.shuwei.wificollecttool;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.shuwei.location.wificollect.WifiCollectListener;
import com.shuwei.location.wificollect.WifiCollector;
import com.shuwei.location.wificollect.WifiItem;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity implements WifiCollectListener<WifiItem>,
        View.OnClickListener {

    private Toast toast;
    private WifiCollector wifiCollector;
    private TextView textView;
    private TextView textView2;
    private Button btnCollect;
    private Button btnStart;
    private Button btnStop;

    private SimpleDateFormat sdf;
    private Date date;
    private RecyclerView recyclerView;
    private HomeAdapter homeAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.textView);
        textView2 = findViewById(R.id.textView2);
        btnCollect = findViewById(R.id.btn_collect);
        btnCollect.setText(COLLECT_COUNT + "次");
        btnStart = findViewById(R.id.btn_start);
        btnStop = findViewById(R.id.btn_stop);
        recyclerView = findViewById(R.id.recyclerView);
        homeAdapter = new HomeAdapter(R.layout.item, new ArrayList());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(homeAdapter);

        btnCollect.setOnClickListener(this);
        btnStart.setOnClickListener(this);
        btnStop.setOnClickListener(this);
        executorService = Executors.newSingleThreadExecutor();
        sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        date = new Date();

        wifiCollector = new WifiCollector.Builder<WifiItem>(this)
                .setWifiCollectListener(this)//设置回调
                .setConverter(new WifiCollector.Converter<WifiItem>() {
                    @Override
                    public WifiItem convert(ScanResult scanResult) {
                        WifiItem wifiItem = new WifiItem();
                        wifiItem.setBssid(scanResult.BSSID);
                        wifiItem.setRssi(scanResult.level);
                        wifiItem.setSsid(scanResult.SSID);
                        return wifiItem;
                    }
                })//设置转换器,转换成自己需要的bean
//                .setSortTarget(WifiCollector.Config.SORT_TARGET_RSSI)//设置排序
//                .setSortType(WifiCollector.Config.SORT_TYPE_Z2A_9TO0_STRONGTOWEAK)//设置排序
//                .setCount(15)//设置需要前多少位
                .create();
    }

    public static final int CASE_COLLECT = 0;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case CASE_COLLECT:
                    if (!isStopClick) {
                        wifiCollector.collect(null);
                    }
                    break;
            }
            return true;
        }
    });

    private File makeFile(File dir, boolean isAppend) {
        if (isAppend) {
            File[] files = dir.listFiles();
            if (files.length <= 0) {
                String txtFileName = System.currentTimeMillis() + ".xls";
                File file = new File(dir, txtFileName);
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return file;
            } else if(files.length==1){
                return files[0];
            }
            File lastModifiedFile = files[0];
            for (int i = 0; i < files.length; i++) {
                if (i == 0) {
                    continue;
                }
                File file = files[i];
                if (lastModifiedFile.lastModified() < file.lastModified()) {
                    lastModifiedFile = file;
                }
            }
            return lastModifiedFile;
        } else {
            String txtFileName = System.currentTimeMillis() + ".xls";
            File file = new File(dir, txtFileName);
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file;
        }
    }

    private File makeDir() {
        File rootDir = Environment.getExternalStorageDirectory().getAbsoluteFile();
        File dir = new File(rootDir, "SW_WifiCollectTool");
        File dirSingle = new File(dir, "distribute");
        dirSingle.mkdirs();
        return dirSingle;
    }

    private ExecutorService executorService;

    private int rssiCount = 1;

    @Override
    public void wifiCollectSuccess(List<WifiItem> wifiItemList) {
        long l = System.currentTimeMillis();
        WifiDistributedNeedHolder.getInstance().setTime(l);
        if (mode == Mode.SIXTY_TIMES) {
            for (int i = 0; i < wifiItemList.size(); i++) {
                WifiItem wifiItem = wifiItemList.get(i);
                WifiHolder wifiHolder = new WifiHolder(l, wifiItem);
                WifiDistributedNeedHolder.getInstance().put(wifiItem.getBssid(), wifiHolder);
            }
            collectCount++;
            updateNotice("第" + collectCount + "次\n已获取AP数量" + WifiDistributedNeedHolder.getInstance().size());
            if (collectCount < COLLECT_COUNT) {
                handler.sendEmptyMessageDelayed(CASE_COLLECT, 1000);
            } else if (collectCount == COLLECT_COUNT) {
                collectCount = 0;
                mode = Mode.TARGET_COLLECT;
                btnCollect.setEnabled(false);
                btnStart.setEnabled(true);
            }
        } else if (mode == Mode.TARGET_COLLECT) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(l + "\r\n");
            for (int i = 0; i < wifiItemList.size(); i++) {
                WifiItem wifiItem = wifiItemList.get(i);
                String mac = wifiItem.getBssid();
                //更新已经已有的
                if (WifiDistributedNeedHolder.getInstance().contains(mac)) {
                    WifiHolder wifiHolder = new WifiHolder(l, wifiItem);
                    WifiDistributedNeedHolder.getInstance().put(mac, wifiHolder);
                }
                stringBuffer.append(wifiItem.toString());
            }
            homeAdapter.addData(stringBuffer.toString());
            recyclerView.post(new Runnable() {
                @Override
                public void run() {
                    recyclerView.scrollToPosition(homeAdapter.getItemCount() - 1);
                }
            });
            collectCount2++;
            updateNotice2("第" + collectCount2 + "次");
            Map<String, WifiHolder> wifiHolders = WifiDistributedNeedHolder.getInstance().getWifiHolders();
            //有序map
            Map<String, Object[]> rssiMap = new TreeMap<>();
            Object[] rssis = new Object[wifiHolders.size()];
            Set<Map.Entry<String, WifiHolder>> entries = wifiHolders.entrySet();
            Iterator<Map.Entry<String, WifiHolder>> iterator = entries.iterator();

            long newTime = WifiDistributedNeedHolder.getInstance().getTime();
            int count = 0;
            while (iterator.hasNext()) {
                Map.Entry<String, WifiHolder> next = iterator.next();
                String mac = next.getKey();
                WifiHolder wifiHolder = next.getValue();
                long time = wifiHolder.getTime();
                if (newTime == time) {
                    if (App.DEBUG) {
                        rssis[count] = mac + ":" + wifiHolder.getWifiItem().getRssi();
                    } else {
                        rssis[count] = wifiHolder.getWifiItem().getRssi();
                    }
                } else {
                    if (App.DEBUG) {
                        rssis[count] = mac + ":" + "0";
                    } else {
                        rssis[count] = "0";
                    }
                }
                count++;
            }
            rssiMap.put(rssiCount + "", rssis);
            File dir = makeDir();
            File file = makeFile(dir, true);
            try {
                WriteSheet.writeRssis(file, rssiMap, rssiCount);
                rssiCount++;
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!isStopClick) {
                handler.sendEmptyMessageDelayed(CASE_COLLECT, 1000);
            }
        }
    }

    private Object[] getTitles(Map<String, WifiHolder> wifiHolders) {
        Object[] titles = new Object[wifiHolders.size()];
        Set<Map.Entry<String, WifiHolder>> entries = wifiHolders.entrySet();
        Iterator<Map.Entry<String, WifiHolder>> iterator = entries.iterator();
        int count = 0;
        while (iterator.hasNext()) {
            Map.Entry<String, WifiHolder> next = iterator.next();
            String mac = next.getKey();
            titles[count] = mac;
            count++;
        }
        return titles;
    }

    @Override
    public void wifiCollectFail(int type, String msg) {
        switch (type) {
            case WifiCollector.TYPE_FAIL_WIFI_ERROR_OCCUR:
                showToast("TYPE_FAIL_WIFI_ERROR_OCCUR" + msg);
                break;
            case WifiCollector.TYPE_FAIL_WIFI_SWITCH_OFF:
                showToast("TYPE_FAIL_WIFI_SWITCH_OFF" + msg);
                break;
            default:
                break;
        }
    }

    public enum Mode {
        SIXTY_TIMES, TARGET_COLLECT
    }

    private Mode mode = Mode.SIXTY_TIMES;
    private static final int COLLECT_COUNT = 60;
    private int collectCount = 0;
    private int collectCount2 = 0;

    public void updateNotice(String s) {
        textView.setText(s);
    }

    public void updateNotice2(String s) {
        textView2.setText(s);
    }

    public void showToast(String s){
        if (toast==null) {
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.setText(s);
        toast.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_collect:
                homeAdapter = new HomeAdapter(R.layout.item, new ArrayList());
                recyclerView.setAdapter(homeAdapter);
                collectCount = 0;
                WifiDistributedNeedHolder.getInstance().getWifiHolders().clear();
                isStopClick = false;
                btnCollect.setEnabled(false);
                btnStart.setEnabled(false);
                btnStop.setEnabled(false);
                wifiCollector.collect(null);
                break;
            case R.id.btn_start:
                btnCollect.setEnabled(false);
                btnStart.setEnabled(false);
                btnStop.setEnabled(true);
                File dir = makeDir();
                File file = makeFile(dir, false);
                Map<String, WifiHolder> wifiHolders = WifiDistributedNeedHolder.getInstance().getWifiHolders();
                Object[] titles = getTitles(wifiHolders);
                try {
                    WriteSheet.writeTitles(file, titles);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.sendEmptyMessageDelayed(CASE_COLLECT, 1000);
                break;
            case R.id.btn_stop:
                isStopClick = true;
                collectCount2 = 0;
                rssiCount = 1;
                btnCollect.setEnabled(true);
                btnStart.setEnabled(false);
                btnStop.setEnabled(false);
                mode = Mode.SIXTY_TIMES;
                WifiDistributedNeedHolder.getInstance().getWifiHolders().clear();
                break;
            default:
                break;
        }
    }

    boolean isStopClick = false;

    public class HomeAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        public HomeAdapter(int layoutResId, List data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tv_data, item);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            /*
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
            * */
            String[] strings = {
                    /*Manifest.permission.BLUETOOTH_PRIVILEGED,加入这个导致小米手机重复打开权限申请对话框*/
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
            boolean needPermissionRequest = false;
            for (int i = 0; i < strings.length; i++) {
                if (ActivityCompat.checkSelfPermission(this, strings[i]) != PackageManager.PERMISSION_GRANTED) {
                    needPermissionRequest = true;
                    showToast("请允许全部权限");
                    break;
                }
            }
            if (needPermissionRequest) {
                ActivityCompat.requestPermissions(this, strings, 100);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                showToast("您拒绝了权限，请允许全部权限");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    public void onMenuClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_to_single:
                Intent intent = new Intent(this, SingleMainActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.action_to_arithmetic:
                intent = new Intent(this, ArithmeticActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }
}
